package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.BompThirdMchntEntryService;
import cc.rengu.igas.bomp.facade.bean.ViolationInfoBean;
import cc.rengu.igas.bomp.facade.request.WechatRiskMchntQueryRequest;
import cc.rengu.igas.bomp.facade.response.WechatRiskMchntQueryResponse;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.enums.BompTxnNumEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.WechatRiskMapper;
import cc.rengu.redp.bizimpl.upmp.domain.ViolationInfo;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.service.WechatRiskService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.WechatRiskVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;


import java.util.List;


@Service
public class WechatRiskServiceImpl extends ServiceImpl<WechatRiskMapper,ViolationInfo> implements WechatRiskService{

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
//    @Autowired
    private BompThirdMchntEntryService bompThirdMchntEntryService;

    private final static Logger logger = LoggerFactory.getLogger(WechatRiskService.class);



    @Override
    public IPage<ViolationInfoBean> findFromBomp(QueryRequest request, WechatRiskVO wechatRiskVO , String traceNo) {

        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
//        Page<ViolationInfoBean> page;
//        String defaultRows = request.getParameter(BusinessContainer.ECP_DEFAULTROWS_PARA_NAME);
//        if(Common.isBlank(defaultRows)){defaultRows = BusinessContainer.ECP_PAGE_DEFAULTROWS;}
//        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request,Integer.parseInt(defaultRows));

        String instId = wechatRiskVO.getInstId();
        if (Common.isBlank(instId)) {
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())) {
                instId = user.getInstId();
            }
        }else {
            //非运营中心管理员使用与自己所属法人行不符的法人行号查询数据时提示异常
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())
                    && !user.isAdmin()&&!instId.equals(user.getInstId())) {
                logger.error("查询微信风险商户违规列表请求参数与用户身份不符");
//                model.addAttribute("error", "查询微信风险商户违规列表请求参数与用户身份不符");
//                page = new PageImpl<ViolationInfoBean>(Lists.newArrayList(), pageable, 0);
//                model.addAttribute("pageData", page);;
                Page<ViolationInfoBean> page = new Page<>();
                page.setRecords(Lists.newArrayList());
                SortUtil.handlePageSort(request,page,true);
                return page;
            }
        }
        String startDate = wechatRiskVO.getStartDate();
        String endDate = wechatRiskVO.getEndDate();
        String dstChannelType = wechatRiskVO.getDstChannelType();
        String dstChannelId = wechatRiskVO.getDstChannelId();
        if(Common.isBlank(startDate)) {
            logger.info("查询微信风险商户违规列表[StartDate]为空，无法检索数据");
            return null;
        }
        if(Common.isBlank(endDate)) {
            logger.info("查询微信风险商户违规列表[endDate]为空，无法检索数据");
            return null;
        }
        if(Common.isBlank(dstChannelType)) {
            logger.info("查询微信风险商户违规列表[ChannelType]为空，无法检索数据");
            return null;
        }
        if(Common.isBlank(dstChannelId)) {
            logger.info("查询微信风险商户违规列表[dstChannelId]为空，无法检索数据");
            return null;
        }


        WechatRiskMchntQueryRequest req = new WechatRiskMchntQueryRequest();
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.wechatRiskMchntQuery.getType(),instId,null));
        req.setChannelId(dstChannelId);
        req.setChannelType(dstChannelType);
        req.setEndDate(endDate);
        req.setStartDate(startDate);
        req.setPageIndex(request.getPageNum());
        req.setPageSize(request.getPageSize());
        req.setUserId(user.getId());

        try{
            logger.info("微信风险商户违规查询"+BompTxnNumEnum.wechatRiskMchntQuery.getDesc()+"交易请求报文：" + JSON.toJSONString(req));
            Result<WechatRiskMchntQueryResponse> response = bompThirdMchntEntryService.wechatRiskMchntQuery(req);
            System.out.println(JSON.toJSONString(response)+"      *****  ");
            logger.info("微信风险商户违规查询"+BompTxnNumEnum.wechatRiskMchntQuery.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                Page<ViolationInfoBean> page = new Page<>();
                WechatRiskMchntQueryResponse resp = response.getResult();
                List<ViolationInfoBean> list = Lists.newArrayList();
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    logger.info("微信风险商户违规查询"+BompTxnNumEnum.wechatRiskMchntQuery.getDesc()+"交易成功");

                    if(Common.isNotBlank(resp)&& CollectionUtils.isNotEmpty(resp.getViolationInfoList())){
                        list = resp.getViolationInfoList();

                        page.setRecords(list);

//                        page = new PageImpl<ViolationInfoBean>(list,pageable,resp.getTotalRows());
                    }else{
                        page.setRecords(list);
//                        page = new PageImpl<ViolationInfoBean>(list,pageable,0);
                    }
//                    model.addAttribute("error","");
//                    model.addAttribute("pageData", page);
                    SortUtil.handlePageSort(request,page,true);
                    return page;
                }else {
                    logger.error("微信风险商户违规查询"+BompTxnNumEnum.wechatRiskMchntQuery.getDesc()+"交易失败");
                    return page.setRecords(list);
                }

            }else{
                logger.error("微信风险商户违规查询"+BompTxnNumEnum.wechatRiskMchntQuery.getDesc()+"交易没有获得返回信息");
                return null;
            }
        }catch (Exception e){
            logger.error("微信风险商户违规查询"+BompTxnNumEnum.wechatRiskMchntQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RpcException("微信风险商户违规查询"+BompTxnNumEnum.wechatRiskMchntQuery.getDesc()+"交易出现异常",e);
//            return null;
        }

    }

    }
